/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { withRouter } from 'umi';
import { Spin, Card, Anchor, Row, Col, Empty, message } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import leaveGuideIllustration from '@/assets/leave/leaveGuideIllustration.png';
import leaveGuideBannerBg from '@/assets/leave/leaveGuideBannerBg.png';
import { getTabContainer } from '@/utils/utils';

import { CollapseHeader, ProfileCard, WorkHandoverTable, VacationTable } from './components';
import styles from './index.less';
import { getHandoverDetailByOrderId, getSystemTodoList, queryVocationList, getColumnlist } from '../service';

const { Link } = Anchor;

function LeaveGuidance({ location }) {
    const { query } = location;
    const { employeeCode, dimissionOrderId } = query;
    const [hasRequestFlag, setHasRequestFlag] = React.useState(false); // 判断是否已经调过获取假期的接口，避免重复调用
    const [vacationOptions, setVacationOptions] = React.useState({});
    const [vocationList, setVocationList] = React.useState([]);
    const [vacationLoading2, setVacationLoading2] = React.useState(true);

    const { data, loading } = useRequest(() => getHandoverDetailByOrderId(dimissionOrderId), {
        ready: !!dimissionOrderId,
        ...defaultFormatResult
    });
    // const params = {
    //     pageNo: 1,
    //     pageSize: 10000,
    //     taskStatus: '0'
    // };
    // // 获取工作安排--系统待办事项
    // // employeeCode: oa1145573189141659650
    // const { data: systemTododata, loading: systemTodoloading } = useRequest(
    //     () => getSystemTodoList(params, employeeCode),
    //     { ...defaultFormatResult }
    // );
    // 获取假期数据
    const params3 = {
        // companyCode: 'ORG15540490989436999',
        companyCode: data?.dimissionOrderVO.companyCode,
        // employeeCodes: ['oa1420013715800248321'],
        employeeCodes: [employeeCode],
        pageNo: 1,
        pageSize: 50
    };
    const { run: getVocationList, loading: vacationLoading } = useRequest(() => queryVocationList(params3), {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data: data3, msg } = res;
                if (code === 10000) {
                    if (data3.rows[0]?.vocationList.length > 0) {
                        const list = data3.rows[0]?.vocationList
                            .filter(item => vacationOptions[item.leaveCode].openState === '1')
                            .map(item => {
                                // remainDuration:剩余时长， discountingDurationUpperLimit：折现天数
                                // 接口给的都是分钟，展示要分小时、天，传给后台分钟
                                // 一天8小时制
                                const temp = {
                                    holidayName: vacationOptions[item.leaveCode].leaveName,
                                    // remainDuration:
                                    //     item.leaveCode === 'CommonYear'
                                    //         ? (item.value / (8 * 60)).toFixed(2)
                                    //         : Number(item.value),
                                    remainDuration: Number(item.value),
                                    durationType: 1,
                                    holidayCode: item.leaveCode
                                };
                                return temp;
                            });
                        setVocationList([...list]);
                    }
                    setVacationLoading2(false);
                    return data3;
                }
                setVacationLoading2(false);
                message.error(msg);
            }
            setVacationLoading2(false);
            return undefined;
        }
    });
    // 获取假期类型选项
    // useRequest(() => getColumnlist('ORG15540490989436999'), {
    const { run: getVacationType } = useRequest(() => getColumnlist(data?.dimissionOrderVO.companyCode), {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data: data2, msg } = res;
                if (code === 10000) {
                    const options = {};
                    for (let i = 0, len = data2.length; i < len; i += 1) {
                        // options[data2[i].leaveCode] = data2[i].leaveName;
                        options[data2[i].leaveCode] = { leaveName: data2[i].leaveName, openState: data2[i].openState };
                    }
                    setVacationOptions(options);
                    getVocationList();
                    setVacationLoading2(false);
                    return options;
                }
                setVacationLoading2(false);
                message.error(msg);
            }
            setVacationLoading2(false);
            return undefined;
        }
    });
    const workContent = item => (
        <div>
            <div className={styles.itemBox}>待安排的工作任务：</div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
            {/* <div className={styles.itemBox}>请尽快完成以下系统待办事项：</div>
            <WorkHandoverTable systemTododata={systemTododata} loading={systemTodoloading} type="showShort" /> */}
            {/* <div>离职前的绩效评定：</div> */}
        </div>
    );
    const personnelContent = item => {
        const handoverTypesArr = {
            1: '剩余假期处理方式',
            2: '打印离职证明',
            3: '公积金/社保停缴日期',
            4: '薪资结算结果',
            5: '回收准证（针对外籍员工）'
        };
        if (item.matterStatus !== 3 && !hasRequestFlag) {
            setHasRequestFlag(true);
            getVacationType();
        }
        return (
            <div>
                <div className={styles.itemBox}>交接事项：</div>
                <div className={`${styles.itemBox} ${styles.val}`}>1. 确认剩余假期处理方式</div>
                <VacationTable
                    type="detail"
                    value={item.matterStatus === 3 ? item.handoverHolidays : vocationList}
                    vacationLoading={item.matterStatus !== 3 && (vacationLoading || vacationLoading2)}
                />
                {data?.handoverSettings.hrHandoverTypes.map((item2, index) => {
                    if (item2 !== 1) {
                        return (
                            <div className={styles.val}>
                                {index + 1}. {handoverTypesArr[item2]}
                            </div>
                        );
                    }
                    return null;
                })}
                <div className={styles.val} style={{ color: 'red' }}>
                    注：完成全部交接事项后，才可领取离职证明
                </div>
            </div>
        );
    };
    const ITContent = item => (
        <div>
            <div className={styles.itemBox}>请在离职前上交以下资产：</div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
        </div>
    );
    // 行政交接
    const administrationContent = item => (
        <div>
            <div className={styles.itemBox}>请在离职前上交以下资产：</div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
        </div>
    );
    // 财务清算
    const financeContent = item => (
        <div>
            <div style={{ margin: '40px 0px 60px' }}>
                <Empty description="开发中，敬请期待" />
            </div>
        </div>
    );
    const matchObj = {
        1: {
            title: '工作安排',
            department: '用人',
            content: workContent,
            href: 'anchorWork'
        },
        2: {
            title: '人事交接',
            department: '人事',
            content: personnelContent,
            href: 'anchorPersonnel'
        },
        3: {
            title: 'IT 交接',
            department: 'IT',
            content: ITContent,
            href: 'anchorIT'
        },
        4: {
            title: '行政交接',
            department: '行政',
            content: administrationContent,
            href: 'anchorAdministration'
        },
        5: {
            title: '财务清算',
            department: '财务',
            content: financeContent,
            href: 'anchorFinance'
        }
    };
    const Box = (item, index) => (
        <div id={matchObj[item.handoverType].href}>
            <CollapseHeader key={index} title={matchObj[item.handoverType].title} matterStatus={item.matterStatus}>
                {item.handoverType !== 1 && item.handoverType !== 5 && (
                    <div className={styles.itemBox}>
                        交接人：<span className={styles.val}>{item.dealEmployeeName}</span>
                    </div>
                )}
                {matchObj[item.handoverType].content(item)}
            </CollapseHeader>
        </div>
    );
    return (
        <div className={styles.handover_container}>
            {/* <Card title="离职引导" style={{ margin: '16px' }}> */}
            {/* <div className={styles.top_card}>
                <ProfileCard employeeCode={employeeCode} />
            </div> */}
            <Spin spinning={loading}>
                <div className={styles.leaveGuideTitle}>离职引导</div>
                <div className={styles.bannerBox}>
                    <img src={leaveGuideBannerBg} alt="leaveGuideBannerBg" style={{ width: '100%', height: '134px' }} />
                    <div className={styles.bannerContent}>
                        <div className={styles.txtBox}>
                            <div className={styles.leaveGuideBannerTitle}>感谢您一直以来为微微做出的贡献！</div>
                            <div className={styles.leaveGuideBannerTxt}>
                                您的离职日期是
                                <span style={{ color: '#5590F6' }}>{data?.dimissionOrderVO.finalDimissionDate}</span>
                                ，为了让您顺利完成离职交接，特此为您指引如下：
                            </div>
                        </div>
                        <img
                            src={leaveGuideIllustration}
                            alt="leaveGuideIllustration"
                            className={styles.leaveGuideIllustration}
                        />
                    </div>
                </div>
            </Spin>
            <Row gutter={24}>
                <Col span={21}>
                    <Spin spinning={loading}>
                        <div>{data && data.matterDetail.map(item => Box(item))}</div>
                    </Spin>
                </Col>
                <Col span={3}>
                    <Anchor offsetTop={10} style={{ marginLeft: 16 }} getContainer={() => getTabContainer()}>
                        {data &&
                            data.matterDetail.map(item => (
                                <Link
                                    href={`#${matchObj[item.handoverType].href}`}
                                    title={matchObj[item.handoverType].title}
                                />
                            ))}
                    </Anchor>
                </Col>
            </Row>
        </div>
    );
}

export default withRouter(LeaveGuidance);
